import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import type { AssessmentType, BusinessSystem } from '@/types/business';
import { useBusiness } from '@/stores/useBusinessStore';

// Import components
import BusinessCard from '@/components/business/BusinessCard';
import BusinessStatistics from '@/components/business/BusinessStatistics';
import BusinessFilter from '@/components/business/BusinessFilter';
import CreateBusinessModal from '@/components/business/CreateBusinessModal';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';

import { showMessage } from '@/components/common/MessageTip';
import { AxiosError } from 'axios';

const BusinessPage: React.FC = () => {
  const navigate = useNavigate();
  const { 
    businessSystems, 
    statistics, 
    selectedBusiness,
    setSelectedBusiness,
    addBusinessSystem,
    updateBusinessSystem,
    deleteBusinessSystem,
    searchBusinessSystems,
    filterBusinessSystems,
    fetchBusinessSystems
  } = useBusiness();

  const [displayedSystems, setDisplayedSystems] = useState<BusinessSystem[]>(businessSystems || []);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [currentBusinessToEdit, setCurrentBusinessToEdit] = useState<BusinessSystem | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  
  // Delete confirmation modal state
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [businessToDelete, setBusinessToDelete] = useState<BusinessSystem | null>(null);
  
  // Initialize business systems when component mounts
  useEffect(() => {
    fetchBusinessSystems();
  }, [fetchBusinessSystems]);

  // Reset displayed systems when businessSystems changes
  useEffect(() => {
    setDisplayedSystems(businessSystems || []);
  }, [businessSystems]);

  // Handle business selection
  const handleSelectBusiness = (business: BusinessSystem) => {
    setSelectedBusiness(business);
    
    // Navigate to main system page after selection
    navigate('/work');
  };

  // Handle search
  const handleSearch = async (keyword: string) => {
    try {
      const results = await searchBusinessSystems(keyword);
      setDisplayedSystems(results);
    } catch (error) {
      console.error('Error searching business systems:', error);
      // Optionally show error message to user
    }
  };

  // Handle filter
  const handleFilter = async (
    status?: 'in_progress' | 'completed' | 'all',
    type?: AssessmentType | 'all'
  ) => {
    try {
      // Convert 'all' to undefined for the API call
      const statusFilter = status === 'all' ? undefined : status;
      const typeFilter = type === 'all' ? undefined : type;
      
      const results = await filterBusinessSystems(
        statusFilter as 'in_progress' | 'completed' | undefined,
        typeFilter as AssessmentType | undefined
      );
      setDisplayedSystems(results);
    } catch (error) {
      console.error('Error filtering business systems:', error);
      // Fallback to showing all systems on error
      setDisplayedSystems(businessSystems);
    }
  };

  // Handle edit business
  const handleEditBusiness = (business: BusinessSystem) => {
    setCurrentBusinessToEdit(business);
    setIsEditing(true);
    setIsCreateModalOpen(true);
  };
  
  // Handle delete business
  const handleDeleteBusiness = (business: BusinessSystem) => {
    setBusinessToDelete(business);
    setIsDeleteModalOpen(true);
  };
  
  // Confirm delete business
  const confirmDeleteBusiness = async () => {
    if (businessToDelete) {
      try {
        await deleteBusinessSystem(businessToDelete.id);
        setIsDeleteModalOpen(false);
        setBusinessToDelete(null);
      } catch (error) {
        console.error('Error deleting business system:', error);
        // You might want to show an error message to the user here
      }
    }
  };
  
  // Close delete modal
  const closeDeleteModal = () => {
    setIsDeleteModalOpen(false);
    setBusinessToDelete(null);
  };

  // Handle form submission (create or update)
  const handleFormSubmit = async (businessData: Omit<BusinessSystem, 'id' | 'createdAt' | 'status'>) => {
    try {
      if (isEditing && currentBusinessToEdit) {
        // Update existing business
        await updateBusinessSystem(currentBusinessToEdit.id, businessData);
        setIsCreateModalOpen(false);
        setIsEditing(false);
        setCurrentBusinessToEdit(null);
      } else {
        // Create new business
        const newBusinessId = await addBusinessSystem(businessData);
        
        // Automatically select the newly created business system
        if (newBusinessId) {
          setSelectedBusiness(newBusinessId);
          
          // Navigate to main system page
          navigate('/work');
        }
      }
    } catch (error) {
      if(error instanceof AxiosError && error.response){
      showMessage('error', error.response?.data.detail, {
        position: 'top-center',
        autoClose: 3000
      });
    }else{
      showMessage('error', error as string, {
        position: 'top-center',
        autoClose: 3000
      });
    }

      // You might want to show an error message to the user here
    }
  };
  
  // Close modal and reset state
  const handleCloseModal = () => {
    setIsCreateModalOpen(false);
    setIsEditing(false);
    setCurrentBusinessToEdit(null);
  };

  return (
    <div className="container mx-auto px-4 py-8 max-w-6xl">
      <header className="mb-8">
        <h1 className="text-2xl font-bold text-slate-800 mb-2">业务系统选择</h1>
        <p className="text-slate-600">请选择已有评估计划或创建新计划</p>
      </header>

      {/* Statistics Section */}
      <section className="mb-8">
        <BusinessStatistics statistics={statistics} />
      </section>

      {/* Actions and Filters */}
      <section className="mb-6 flex justify-between items-center">
        <BusinessFilter onSearch={handleSearch} onFilter={handleFilter} />
        
        <div className="flex space-x-3">
          <Link
            to="/template"
            className="bg-gray-200 text-gray-800 px-4 py-2 rounded-md hover:bg-gray-300 flex items-center min-h-[44px] transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
              <path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6zM14 9a1 1 0 00-1 1v6a1 1 0 001 1h2a1 1 0 001-1v-6a1 1 0 00-1-1h-2z" />
            </svg>
            管理评估模版
          </Link>
          
          <button
            onClick={() => setIsCreateModalOpen(true)}
            className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 flex items-center min-h-[44px] transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clipRule="evenodd" />
            </svg>
            新建评估计划
          </button>
        </div>
      </section>

      {/* Business Systems Grid */}
      <section>
        {displayedSystems?.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {(displayedSystems || []).map(business => (
              <div key={business.id} className="relative group">
                <BusinessCard
                  business={business}
                  isSelected={business.id === selectedBusiness?.id}
                  onClick={() => handleSelectBusiness(business)}
                />
                <div className="absolute top-2 right-2 flex space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  {/* Edit button */}
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEditBusiness(business);
                    }}
                    className="p-2 bg-white rounded-full shadow-md hover:bg-gray-100"
                    title="编辑评估计划"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                  </button>
                  
                  {/* Delete button */}
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteBusiness(business);
                    }}
                    className="p-2 bg-white rounded-full shadow-md hover:bg-red-50"
                    title="删除评估计划"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-16 bg-slate-50 rounded-lg border border-slate-200">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-16 w-16 mx-auto text-slate-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <h3 className="text-lg font-medium text-slate-700 mb-2">暂无评估计划</h3>
            <p className="text-slate-500 mb-4">点击"新建评估计划"按钮创建一个新的评估计划</p>
            <button
              onClick={() => setIsCreateModalOpen(true)}
              className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 inline-flex items-center min-h-[44px]"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clipRule="evenodd" />
              </svg>
              新建评估计划
            </button>
          </div>
        )}
      </section>

      {/* Create/Edit Business Modal */}
      <CreateBusinessModal
        isOpen={isCreateModalOpen}
        onClose={handleCloseModal}
        onSubmit={handleFormSubmit}
        businessToEdit={currentBusinessToEdit}
        isEditing={isEditing}
      />
      
      {/* Delete Confirmation Modal */}
      <DeleteConfirmModal 
        isOpen={isDeleteModalOpen}
        onClose={closeDeleteModal}
        onConfirm={confirmDeleteBusiness}
        itemName={businessToDelete?.name || ''}
        message="您确定要删除以下评估计划吗？"
      />
    </div>
  );
};

export default BusinessPage;
